<template>
  <div class="page-container">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>编辑项目</h2>
      <button class="btn btn-outline-secondary" @click="goBack">
        <i class="bi bi-arrow-left me-1"></i> 返回项目详情
      </button>
    </div>

    <div v-if="loading" class="d-flex justify-content-center align-items-center" style="height: 300px;">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
    </div>

    <div v-else class="card">
      <div class="card-body">
        <form @submit.prevent="submitForm">
          <!-- 表单分组：基本信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">基本信息</h4>
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label required">项目名称</label>
                <input type="text" class="form-control" v-model="formData.name" required>
                <div class="invalid-feedback" v-if="errors.name">{{ errors.name }}</div>
              </div>
              <div class="col-md-4">
                <label class="form-label">工程代号</label>
                <input type="text" class="form-control" v-model="formData.project_code">
                <div class="invalid-feedback" v-if="errors.project_code">{{ errors.project_code }}</div>
              </div>
              <div class="col-md-4">
                <label class="form-label">项目序号</label>
                <input type="number" class="form-control" v-model="formData.project_number">
              </div>
              <div class="col-md-4">
                <label class="form-label required">项目阶段</label>
                <select class="form-select" v-model="formData.status" required>
                  <option value="">请选择项目阶段</option>
                  <option v-for="status in projectStatusOptions" :key="status" :value="status">{{ status }}</option>
                </select>
                <div class="invalid-feedback" v-if="errors.status">{{ errors.status }}</div>
              </div>
              <div class="col-md-4">
                <label class="form-label">阶段状态</label>
                <select class="form-select" v-model="formData.phase_status">
                  <option value="">请选择阶段状态</option>
                  <option v-for="status in phaseStatusOptions" :key="status" :value="status">{{ status }}</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">建设地点</label>
                <input type="text" class="form-control" v-model="formData.location" placeholder="多个地点用逗号分隔">
              </div>
              <div class="col-12">
                <label class="form-label">项目描述/建设内容</label>
                <textarea class="form-control" v-model="formData.description" rows="3"></textarea>
              </div>
            </div>
          </div>

          <!-- 表单分组：任务书信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">任务书信息</h4>
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label">任务书文号</label>
                <input type="text" class="form-control" v-model="formData.task_document_no">
              </div>
              <div class="col-md-4">
                <label class="form-label">规划类型</label>
                <input type="text" class="form-control" v-model="formData.planning_type">
              </div>
              <div class="col-md-4">
                <label class="form-label">建设类型</label>
                <select class="form-select" v-model="formData.construction_type">
                  <option value="">请选择建设类型</option>
                  <option v-for="type in constructionTypeOptions" :key="type" :value="type">{{ type }}</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">任务书下达时间</label>
                <input type="date" class="form-control" v-model="formData.task_issue_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">任务书要求完成时间</label>
                <input type="date" class="form-control" v-model="formData.required_completion_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">上级延期完成时间</label>
                <input type="date" class="form-control" v-model="formData.extended_completion_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">总投资(万元)</label>
                <input type="number" class="form-control" v-model="formData.total_investment" step="0.01">
              </div>
              <div class="col-md-4">
                <label class="form-label">直接费(万元)</label>
                <input type="number" class="form-control" v-model="formData.direct_cost" step="0.01">
              </div>
            </div>
          </div>

          <!-- 表单分组：合同信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">合同信息</h4>
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label">发包模式</label>
                <input type="text" class="form-control" v-model="formData.bidding_mode" placeholder="请输入发包模式">
              </div>
              <div class="col-md-4">
                <label class="form-label">合同开工日期</label>
                <input type="date" class="form-control" v-model="formData.contract_start_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">合同竣工日期</label>
                <input type="date" class="form-control" v-model="formData.contract_end_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">合同工期(天)</label>
                <input type="number" class="form-control" v-model="formData.contract_duration">
              </div>
              <div class="col-md-4">
                <label class="form-label">施工合同价(元)</label>
                <input type="number" class="form-control" v-model="formData.contract_amount" step="0.01">
              </div>
              <div class="col-md-4" v-if="formData.status && formData.status.startsWith('施工-')">
                <label class="form-label">施工进度(%)</label>
                <input type="number" class="form-control" v-model="formData.progress" min="0" max="100" step="0.1">
              </div>
            </div>
          </div>

          <!-- 表单分组：参建单位信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">参建单位信息</h4>
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label">勘察设计单位</label>
                <input type="text" class="form-control" v-model="formData.survey_design_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">造价编制单位</label>
                <input type="text" class="form-control" v-model="formData.cost_compilation_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">造价审核单位</label>
                <input type="text" class="form-control" v-model="formData.cost_audit_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">施工单位</label>
                <input type="text" class="form-control" v-model="formData.construction_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">使用单位类型</label>
                <select class="form-select" v-model="formData.using_unit_type">
                  <option value="">请选择使用单位类型</option>
                  <option value="中心及下属单位">中心及下属单位</option>
                  <option value="代供单位">代供单位</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">使用单位名称</label>
                <input type="text" class="form-control" v-model="formData.using_unit" placeholder="请输入使用单位名称">
              </div>
              <div class="col-md-4">
                <label class="form-label">监理单位</label>
                <input type="text" class="form-control" v-model="formData.supervision_unit">
              </div>
            </div>
          </div>

          <!-- 表单分组：联系信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">联系信息</h4>
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">现场联系人</label>
                <input type="text" class="form-control" v-model="formData.field_contact">
              </div>
              <div class="col-md-6">
                <label class="form-label">联系电话</label>
                <input type="text" class="form-control" v-model="formData.contact_phone">
              </div>
            </div>
          </div>

          <!-- 表单分组：其他信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">其他信息</h4>
            <div class="row g-3">
              <div class="col-12">
                <label class="form-label">备注信息</label>
                <textarea class="form-control" v-model="formData.notes" rows="3"></textarea>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="d-flex justify-content-end mt-4">
            <button type="button" class="btn btn-outline-secondary me-2" @click="goBack">
              <i class="bi bi-x-circle me-1"></i> 取消
            </button>
            <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
              <i class="bi bi-check-circle me-1"></i> 
              <span v-if="isSubmitting">保存中...</span>
              <span v-else>保存修改</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const { ipcRenderer } = require('electron')

// 获取router和route实例
const router = useRouter()
const route = useRoute()

// 项目ID
const projectId = ref(parseInt(route.params.id))

// 加载状态
const loading = ref(true)
const isSubmitting = ref(false)

// 表单数据
const formData = reactive({
  project_number: null,
  project_code: '',
  name: '',
  description: '',
  location: '',
  status: '',
  sub_status: '',
  progress: 0,
  phase_status: '',
  task_document_no: '',
  planning_type: '',
  construction_type: '',
  total_investment: null,
  direct_cost: null,
  task_issue_date: '',
  required_completion_date: '',
  extended_completion_date: '',
  contract_start_date: '',
  contract_end_date: '',
  contract_duration: null,
  contract_amount: null,
  bidding_mode: '',
  survey_design_unit: '',
  cost_compilation_unit: '',
  cost_audit_unit: '',
  construction_unit: '',
  supervision_unit: '',
  using_unit_type: '',
  using_unit: '',
  construction_type: '',
  field_contact: '',
  contact_phone: '',
  notes: ''
})

// 表单错误信息
const errors = reactive({})

// 选项数据
const projectStatusOptions = ref([])
const phaseStatusOptions = ref(['正常进行', '阶段性迟缓', '滞后', '其他'])
const constructionTypeOptions = ref(['统建', '代建'])

// 获取项目数据
async function fetchProjectData() {
  try {
    loading.value = true
    const response = await window.api.database.getProject(projectId.value)
    
    if (response.success) {
      // 填充表单数据
      const projectData = response.data.project
      
      // 遍历项目数据的所有字段，填充到表单数据中
      Object.keys(projectData).forEach(key => {
        // 跳过id、created_at和updated_at字段
        if (key !== 'id' && key !== 'created_at' && key !== 'updated_at') {
          formData[key] = projectData[key]
        }
      })
      
      console.log('项目数据加载成功:', projectData)
    } else {
      console.error('获取项目数据失败:', response.error)
      alert(`获取项目数据失败: ${response.error}`)
      goBack()
    }
  } catch (error) {
    console.error('获取项目数据失败:', error)
    alert(`获取项目数据失败: ${error.message}`)
    goBack()
  } finally {
    loading.value = false
  }
}

// 获取系统设置
async function fetchSettings() {
  try {
    const response = await window.api.database.getSettings('project')
    
    if (response.success) {
      // 获取项目状态选项
      const projectStatusSetting = response.data.find(item => item.key === 'default_project_status')
      if (projectStatusSetting && projectStatusSetting.value) {
        projectStatusOptions.value = projectStatusSetting.value.split(',')
      }
      
      // 获取阶段状态选项
      const phaseStatusSetting = response.data.find(item => item.key === 'default_phase_status')
      if (phaseStatusSetting && phaseStatusSetting.value) {
        phaseStatusOptions.value = phaseStatusSetting.value.split(',')
      }
      
      // 获取建设类型选项
      const constructionTypeSetting = response.data.find(item => item.key === 'default_construction_types')
      if (constructionTypeSetting && constructionTypeSetting.value) {
        constructionTypeOptions.value = constructionTypeSetting.value.split(',')
      }
    }
  } catch (error) {
    console.error('获取系统设置失败:', error)
  }
}

// 添加焦点事件监听
const setupFocusDebug = () => {
  const debugFocus = (e) => {
    // console.log('[Focus Debug]', {
    //   type: e.type,
    //   target: e.target.tagName,
    //   targetId: e.target.id,
    //   targetType: e.target.type,
    //   timestamp: new Date().toISOString()
    // })
  }

  document.addEventListener('focus', debugFocus, true)
  document.addEventListener('blur', debugFocus, true)
  document.addEventListener('focusin', debugFocus, true)
  document.addEventListener('focusout', debugFocus, true)

  // 监听主进程发来的窗口焦点变化
  window.electron.ipcRenderer.on('window-focus-changed', (focused) => {
    console.log('[Window Focus Changed]', {
      focused,
      timestamp: new Date().toISOString()
    })
  })

  return () => {
    document.removeEventListener('focus', debugFocus, true)
    document.removeEventListener('blur', debugFocus, true)
    document.removeEventListener('focusin', debugFocus, true)
    document.removeEventListener('focusout', debugFocus, true)
    window.electron.ipcRenderer.removeAllListeners('window-focus-changed')
  }
}

onMounted(() => {
  const cleanup = setupFocusDebug()
  onUnmounted(cleanup)
})

// 修改提交表单的函数
const submitForm = async () => {
  try {
    isSubmitting.value = true  // 添加提交状态控制
    
    console.log('\n====================== 项目表单提交 ======================')
    console.log('┌─────────────────────────────────────────────────────────┐')
    console.log('│                     基本信息                            │')
    console.log('└─────────────────────────────────────────────────────────┘')
    console.log('时间:', new Date().toLocaleString())
    console.log('项目ID:', projectId.value)
    
    console.log('\n[Form Submit] Starting form submission')
    console.log('\n[Form Submit] Form data before submission:', {
      project_number: formData.project_number,
      project_code: formData.project_code,
      name: formData.name,
      description: formData.description,
      location: formData.location
    })

    console.log('\n[Form Submit] Active element before save:', document.activeElement?.tagName)
    
    let result
    try {
      result = await ipcRenderer.invoke('update-project', {
        id: projectId.value,
        ...formData
      })
      console.log('\n[Form Submit] IPC call result:', result)
    } catch (ipcError) {
      console.error('\n❌ IPC调用失败:', ipcError)
      console.log('====================== IPC错误 ======================\n')
      alert(`保存失败: ${ipcError.message}`)
      return
    }
    
    if (result.success) {
      router.push(`/project-detail/${projectId.value}`)
    } else {
      console.error('\n❌ 表单提交失败:', result.error)
      console.log('数据库错误详情:', result.error)
      console.log('====================== 提交失败 ======================\n')
      
      // 显示错误弹窗
      alert(`保存失败: ${result.error}`)
    }
  } catch (error) {
    console.error('\n❌ 表单提交出错:', error)
    console.log('错误类型:', error.constructor.name)
    console.log('错误信息:', error.message)
    console.log('错误堆栈:', error.stack)
    console.log('====================== 提交错误 ======================\n')
    
    // 显示错误弹窗
    alert(`保存失败: ${error.message}`)
  } finally {
    isSubmitting.value = false  // 重置提交状态
  }
}

// 返回项目详情页
function goBack() {
  router.push(`/project-detail/${projectId.value}`)
}

// 生命周期钩子
onMounted(async () => {
  await Promise.all([fetchSettings(), fetchProjectData()])
})
</script>

<style scoped>
.form-section {
  border: 1px solid #e9ecef;
  border-radius: 0.25rem;
  padding: 1.5rem;
  background-color: #f8f9fa;
}

.form-section-title {
  margin-top: -2.5rem;
  margin-bottom: 1rem;
  background-color: #fff;
  display: inline-block;
  padding: 0.5rem 1rem;
  border: 1px solid #e9ecef;
  border-radius: 0.25rem;
  font-size: 1.1rem;
  font-weight: 600;
}

.required::after {
  content: " *";
  color: #dc3545;
}

.invalid-feedback {
  display: block;
}
</style> 